<?php
namespace RTSCraft\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use RTSCraft\MainBundle\Entity\Ressources;
use RTSCraft\MainBundle\Entity\Element;
use RTSCraft\MainBundle\Entity\Factions;
use RTSCraft\MainBundle\Entity\Statistics;
use RTSCraft\MainBundle\Entity\Category;
use RTSCraft\MainBundle\Entity\Article;
use RTSCraft\MainBundle\Entity\Version;

class ManagementController extends Controller
{
  /* Generates the index page */
  public function indexAction()
  {
    // Generate the "tree" :
    $tree = array("Factions" => $this->summarizeNames($this->getFactions()),
		  "Resources" => $this->summarizeNames($this->getResources()),
		  "Statistics" => $this->summarizeNames($this->getStatistics()));

    foreach ($this->getCategories() as $c)
      {
	$tree[$c->getName()] = $this->summarizeNames($this->getElementsByCategory($c->getName()));
      }

    // Send the trees :
    return $this->render('RTSCraftMainBundle:Admin:management.html.twig',
			 array("tree" => $tree, "info" => $this->info_str));
  }

  /**
   * @Route("/add", name="operation")
   * @Template()
   */
  public function addAction()
  {
    $entity = null;
    $res = null;
    $req = $this->get('request');
    $em = $this->getDoctrine()->getEntityManager();
    // Call the right method to perform the action.
    if ($req->get("val") == "null")
      {
	$this->info_str = "Name cannot be empty !";
	return $this->indexAction();
      }
    switch ($req->get("cate"))
      {
      case "RTSCraftTreeRoot":
	$res = new Category();
	$repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Category');
	$results = $repo->findBy(array('name' => $req->get('val')));
	if (!empty($results))
	  {
	    $result = reset($results);
	    $result->setDeleted(false);
	    $em->persist($result);
	    $em->flush();
	    return $this->indexAction();
	  }

	break;
	// Special cases :
      case "Factions":
	$res = new Factions();
	$repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Factions');
	$results = $repo->findBy(array('name' => $req->get('val')));
	if (!empty($results))
	  {
	    $result = reset($results);
	    $result->setDeleted(false);
	    $em->persist($result);
	    $em->flush();
	    return $this->indexAction();
	  }
	break;
      case "Resources":
	$res = new Ressources();
	$repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Ressources');
	$results = $repo->findBy(array('name' => $req->get('val')));
	if (!empty($results))
	  {
	    $result = reset($results);
	    $result->setDeleted(false);
	    $em->persist($result);
	    $em->flush();
	    return $this->indexAction();
	  }
	break;
      case "Statistics":
	$res = new Statistics();
	$repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Statistics');
	$results = $repo->findBy(array('name' => $req->get('val')));
	if (!empty($results))
	  {
	    $result = reset($results);
	    $result->setDeleted(false);
	    $em->persist($result);
	    $em->flush();
	    return $this->indexAction();
	  }

	break;
      default:
	$cat = $this->getCategoryByName($req->get("cate"));

	/* Check if the element already exists */
	$repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Element');
	$results = $repo->findBy(array('name' => $req->get('val')));

	if (!empty($results))
	  {
	    /* yes */
	    $result = reset($results);
	    $result->setDeleted(false);
	    $em->persist($result);
	    return $this->indexAction();
	  }

	$res = new Element();
	$res->setCategory($cat);

	$ver = new Version();
	$ver->setNumVersion(1);
	$ver->setIp("127.0.0.1");
	$ver->setDate(new \DateTime('now'));
	$ver->setText("This is an auto-generated stub for the " .
		     "article about: " . $req->get("val") . ".");
	$ver->setAuthor("Admin");

	$art = new Article();
	$art->setTitle($req->get("val"));
	$art->setElement($res);

	$em->persist($res);
	$em->persist($art);


	$em->persist($ver);
	$art->addVersion($ver);

	$ver->setArticleId($art);

	$em->persist($art);
	$em->persist($ver);

	break;
      }

    if ($res != null)
      {
	if (method_exists($res, 'setImgURL'))
	  $res->setImgURL("");
	if (method_exists($res, 'setDeleted'))
	  $res->setDeleted(false);
	$res->setName($req->get("val"));
	try {
	  $em->persist($res);
	} catch (Exception $e)
	    {}
      }

    // index page
    $em->flush();
    return $this->indexAction();
  }

  /**
   * @Route("/remove", name="operation")
   * @Template()
   */
  public function removeAction()
  {
    $entity = null;
    $req = $this->get('request');
    $sub = $req->get('sub');
    $cate = $req->get("cate");
    $em = $this->getDoctrine()->getEntityManager();
    // Call the right method to perform the action.
    if ($sub == "null")
      switch ($cate)
	{
	  // Unremovables :
	case "RTSCraftTreeRoot":
	case "Factions":
	case "Resources":
	case "Statistics":
	  $info_str = "Cannot remove builtin type " . $cate;
	  break;
	default:
	  $cat = $this->getCategoryByName($req->get("cate"));
	  $cat->setDeleted(true);
	  $em->persist($cat);
	  break;
	}
    else
      {
	// If the element is a node :
      switch ($cate)
	{
	case "Factions":
	  $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Factions');
	  break;
	case "Resources":
	  $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Ressources');
	  break;
	case "Statistics":
	  $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Statistics');
	  break;
	default:
	  $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Element');
	  break;
	}
      $e = $repo->findBy(array ("name" => $sub));
      $e[0]->setDeleted(true);
      $em->persist($e[0]);
      }

    $em->flush();
    // index page
    return $this->indexAction();    
  }

  public function getResources()
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Ressources');
    
    $results = $repo->findBy(array("deleted" => false));
    
    return $results;
  }
  
  public function getCategories()
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Category');
    
    $results = $repo->findBy(array("deleted" => false));
      
    return $results;
  }

  public function getCategoryByName($n)
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Category');
    
    $result = $repo->findByName($n);
      
    return $result[0];
  }

  public function getFactions()
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Factions');
    
    $results = $repo->findBy(array("deleted" => false));
      
    return $results;
  }

  public function getStatistics()
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Statistics');
    
    $results = $repo->findBy(array("deleted" => false));
      
    return $results;
  }

  public function getElementsByCategory($n)
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Element');
    
    $results = $repo->findByCategory($n);
    return $results;
  }

  public function getElementByName($n)
  {
    $repo = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Element');
    
    $results = $repo->findBy(array("name" => $n, "deleted" => false));

    return $results;
  }

  // Returns a list of the names of the given object list, or pushes them in the second agrument if it exists.
  protected function summarizeNames($list, $arr = null)
  {
    if ($arr != null)
      $res = $arr;
    else
      $res = array();
    foreach ($list as $e)
      {
	array_push($res, $e->getName());
      }
    return $res;
  }

  private $info_str;
}
